import React, { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import {
  Card,
  Form,
  Input,
  Button,
  Typography,
  Alert,
  Space,
  Divider,
  Progress,
  Tooltip
} from 'antd';
import {
  LockOutlined,
  UserOutlined,
  SafetyOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone,
  CheckCircleOutlined,
  InfoCircleOutlined,
  GiftOutlined
} from '@ant-design/icons';

import { useAuth } from '../contexts/AuthContext';
import { useWallet } from '../contexts/WalletContext';

const { Title, Text } = Typography;

const Register = () => {
  const [form] = Form.useForm();
  const [isLoading, setIsLoading] = useState(false);
  const [passwordStrength, setPasswordStrength] = useState(0);
  const [passwordFeedback, setPasswordFeedback] = useState([]);
  const navigate = useNavigate();

  const { register } = useAuth();
  const { account } = useWallet();

  const urlParams = new URLSearchParams(window.location.search);
  const referralCode = urlParams.get('ref');

  const calculatePasswordStrength = (password) => {
    let strength = 0;
    const feedback = [];

    if (password.length >= 8) {
      strength += 25;
    } else {
      feedback.push('At least 8 characters');
    }

    if (/[A-Z]/.test(password)) {
      strength += 25;
    } else {
      feedback.push('One uppercase letter');
    }

    if (/[a-z]/.test(password)) {
      strength += 25;
    } else {
      feedback.push('One lowercase letter');
    }

    if (/[0-9]/.test(password)) {
      strength += 25;
    } else {
      feedback.push('One number');
    }

    setPasswordStrength(strength);
    setPasswordFeedback(feedback);
  };

  const getPasswordStrengthColor = () => {
    if (passwordStrength < 25) return '#ff4d4f';
    if (passwordStrength < 50) return '#faad14';
    if (passwordStrength < 75) return '#1890ff';
    return '#52c41a';
  };

  const getPasswordStrengthText = () => {
    if (passwordStrength < 25) return 'Very Weak';
    if (passwordStrength < 50) return 'Weak';
    if (passwordStrength < 75) return 'Good';
    return 'Strong';
  };

  const handlePasswordChange = (e) => {
    const password = e.target.value;
    calculatePasswordStrength(password);
  };

  const handleSubmit = async (values) => {
    if (!account) {
      return;
    }

    setIsLoading(true);
    try {
      const success = await register(values.password, referralCode);
      if (success) {
        navigate('/dashboard');
      }
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center py-12 px-4">
      <div className="max-w-md w-full">
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 bg-blue-600 rounded-full mb-4">
            <SafetyOutlined className="text-3xl text-white" />
          </div>
          <Title level={2} className="text-gray-900 mb-2">
            Create Account
          </Title>
          <Text className="text-gray-600">
            Join the God Token staking community and start earning rewards
          </Text>
        </div>

        {referralCode && (
          <Alert
            message="Referral Code Applied"
            description={`You're registering with referral code: ${referralCode}`}
            type="success"
            showIcon
            className="mb-6"
          />
        )}

        <Card className="shadow-lg border-0">
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
            requiredMark={false}
          >
            <Form.Item>
              <Alert
                message="Connected Wallet"
                description={
                  <div className="flex items-center space-x-2">
                    <UserOutlined />
                    <Text code className="flex-1">
                      {account || 'No wallet connected'}
                    </Text>
                  </div>
                }
                type="info"
                showIcon
              />
            </Form.Item>

            <Form.Item
              label="Password"
              name="password"
              rules={[
                { required: true, message: 'Please enter a password' },
                { min: 8, message: 'Password must be at least 8 characters' }
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="Create a strong password"
                size="large"
                onChange={handlePasswordChange}
                iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
              />
            </Form.Item>

            {passwordStrength > 0 && (
              <Form.Item>
                <div className="space-y-2">
                  <div className="flex justify-between items-center">
                    <Text className="text-sm">Password Strength:</Text>
                    <Text className="text-sm" style={{ color: getPasswordStrengthColor() }}>
                      {getPasswordStrengthText()}
                    </Text>
                  </div>
                  <Progress
                    percent={passwordStrength}
                    strokeColor={getPasswordStrengthColor()}
                    showInfo={false}
                    size="small"
                  />
                  {passwordFeedback.length > 0 && (
                    <div className="mt-2">
                      <Text type="secondary" className="text-xs">
                        Include: {passwordFeedback.join(', ')}
                      </Text>
                    </div>
                  )}
                </div>
              </Form.Item>
            )}

            <Form.Item
              label="Confirm Password"
              name="confirmPassword"
              dependencies={['password']}
              rules={[
                { required: true, message: 'Please confirm your password' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('Passwords do not match'));
                  },
                }),
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="Confirm your password"
                size="large"
                iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
              />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                size="large"
                block
                loading={isLoading}
                disabled={!account}
                className="h-12 bg-blue-600 hover:bg-blue-700 border-0"
              >
                {isLoading ? 'Creating Account...' : 'Create Account'}
              </Button>
            </Form.Item>
          </Form>

          <Divider />

          <div className="text-center">
            <Text type="secondary">
              Already have an account?{' '}
              <Link to="/login" className="text-blue-600 hover:text-blue-700">
                Sign In
              </Link>
            </Text>
          </div>

          <div className="mt-6 text-center">
            <Link to="/connect" className="text-gray-600 hover:text-gray-900">
              ← Back to Wallet Connection
            </Link>
          </div>
        </Card>

        {/* Benefits */}
        <div className="mt-8 bg-white rounded-lg shadow-md p-6">
          <Title level={4} className="text-center mb-4">
            <GiftOutlined className="text-yellow-500 mr-2" />
            Why Join God Token Staking?
          </Title>
          <div className="space-y-3">
            <div className="flex items-start space-x-3">
              <CheckCircleOutlined className="text-green-500 mt-1" />
              <div>
                <Text strong>Earn 1% Daily Rewards</Text>
                <div>
                  <Text type="secondary" className="text-sm">
                    Get daily interest on your staked tokens
                  </Text>
                </div>
              </div>
            </div>
            <div className="flex items-start space-x-3">
              <CheckCircleOutlined className="text-green-500 mt-1" />
              <div>
                <Text strong>10% Referral Bonus</Text>
                <div>
                  <Text type="secondary" className="text-sm">
                    Earn rewards from your direct referrals
                  </Text>
                </div>
              </div>
            </div>
            <div className="flex items-start space-x-3">
              <CheckCircleOutlined className="text-green-500 mt-1" />
              <div>
                <Text strong>Secure & Reliable</Text>
                <div>
                  <Text type="secondary" className="text-sm">
                    Built on Binance Smart Chain with audited smart contracts
                  </Text>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Security Notice */}
        <div className="mt-6 text-center">
          <Alert
            message="Security Notice"
            description={
              <div className="text-left">
                <p className="mb-2">• Store your password securely</p>
                <p className="mb-2">• Never share your login credentials</p>
                <p>• Always verify you're on the official website</p>
              </div>
            }
            type="warning"
            showIcon
            className="inline-block text-left"
          />
        </div>
      </div>
    </div>
  );
};

export default Register;